import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes, asyncRoutes } from "@/router";
import { store } from "@/store";


const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: any, route: RouteRecordRaw) => {
  let result = false;
  if (route.meta && route.meta.policy) {
    const policy = route.meta.policy as string;
    result = roles[policy];
  } else {
    result = true;
  }
  return result;
};

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes asyncRoute
 * @param grantedPolicies 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[], grantedPolicies: any) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmp = { ...route }

    if (hasPermission(grantedPolicies, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, grantedPolicies)
      }

      if (route.meta && route.meta.policy === '') {
        if (tmp.children != null && tmp.children.length > 0) {
          asyncRoutes.push(tmp)
        }
      } else {
        asyncRoutes.push(tmp)
      }
    }
   
  });

  // debugger
  // console.log('asyncRoutes',asyncRoutes);
  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(grantedPolicies: any) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, grantedPolicies)
      setRoutes(accessedRoutes);
      resolve(accessedRoutes)
    });
  }
  return { routes, setRoutes, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
